const app = getApp();

Page({
	data: {
		topAreaHeight: 0,
		selectedAddressIndex: 0, // 默认选中第一个地址
		selectedAddress: {},
		openId: '',
		addressList: [], // 地址列表
		products: [],
		sliderList: [],
		showPopup: false,
		firstVisiable: true,
		mainSlideImgUrl: '',
		couponItems: [
		],
		hasClaimed: false,
		loading: true
	},

	onLoad() {
    wx.showLoading({ title: '加载中' });
    console.log("home1.onLoad.start");
		const { top: topAreaHeight } = wx.getMenuButtonBoundingClientRect();
		console.log('height', topAreaHeight);
		this.setData({
			topAreaHeight: topAreaHeight
		});
    this.initShareMenu(); // 初始化分享菜单
    this.fetchHomeInfo();
	},
	onShow() {
		// console.log("home1.onshow.start");
  },
  
  //
  fetchHomeInfo(){
    // 获取用户地理位置
    wx.getFuzzyLocation({
      type: 'gcj02',
      success: (location) => {
        const { longitude, latitude } = location;
        this.callGetHomeInfo(longitude.toString(), latitude.toString());
      },
      fail: (err) => {
        console.error('获取位置信息失败:', err);
        // 获取位置失败时使用默认值
        this.callGetHomeInfo("0", "0");
      }
    });
  },

  // 调用getHomeInfo云函数
  callGetHomeInfo(longitude, latitude, schoolCode) {
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: { 
        getHomeInfoRequest: {
          longitude,  
          latitude, 
          configNames: ["school_list", "tan_chuang", "home_ui_configs"],
          schoolCode // 如果用户选择了学校，则传递schoolCode
        }
      },
      success: async (result) => {
        console.log("result", result)
        const openId = result.result?.data?.userInfo?.openId;
        this.setData({ openId });
        app.globalData.openId = openId;
        wx.setStorageSync('openId', openId);

        const mainSlideImgUrl = result.result?.data?.configs?.home_ui_configs?.mainSlideImgUrl;
        this.setData({
          mainSlideImgUrl
        })

        // 检查返回的数据结构
        if (!result.result?.data?.addressList) {
          console.error('返回数据缺少addressList字段:', result);
          wx.showToast({ title: '数据格式错误', icon: 'none' });
          return;
        }

        const schools = result.result.data.addressList;
        if (!Array.isArray(schools)) {
          console.error('addressList不是数组:', schools);
          wx.showToast({ title: '数据格式错误', icon: 'none' });
          return;
        }

        const schoolsVo = schools.map((item) => {
          if (!item) {
            console.error('学校数据项为空:', item);
            return null;
          }
          return {
            addressCode: item.addressCode || '',
            addressName: item.addressDesc || '',
            matchCurPosition: item.matchCurPosition || false,
            couponPackageId: "",
            showHomePopUp: false
          };
        }).filter(item => item !== null); // 过滤掉无效的数据项

        this.setData({ addressList: schoolsVo });
        if (schoolsVo.length > 0) {
          let selectedAddressIndex = schoolsVo.findIndex(address => address.matchCurPosition === true);
          selectedAddressIndex = selectedAddressIndex >= 0 ? selectedAddressIndex : 0;
          const selectedAddress = schoolsVo[selectedAddressIndex];
          console.log('selectedAddress.showHomePopUp', selectedAddress.showHomePopUp);
          
          // 缓存默认选中的地址到本地
          wx.setStorageSync('selectedAddress', selectedAddress);
          
          this.setData({
            selectedAddress,
            selectedAddressIndex: selectedAddressIndex,
            showPopup: selectedAddress?.showHomePopUp || false
          })
        } else {
          wx.hideLoading();
          wx.showToast({ title: '地址列表为空', icon: 'none' });
        }

        const couponPackage = result.result?.data?.couponPackage;
        this.setData({
          hasClaimed: couponPackage?.hasClaimed || false,
          couponItems: couponPackage?.couponItems || []
        })

        const products = result.result?.data?.products?.map((item) => ({
          id: item.productId,
          imageUrl: item.imageUrl,
          price: item.price,
          quantity: 1,
          totalPrice: item.price,
          productTitle: item.productTitle,
          participantId: item.participantId,
          status: item.status,
          isFriendToCut: item.isFriendToCut,
          totalAmount: parseFloat(item.totalAmount || 0),
          reducedAmount: parseFloat(item.reducedAmount || 0),
          leftAmount: (item.leftAmount !==null && item.leftAmount !== undefined) ? parseFloat(item.leftAmount): null,
          progressWidth: `${(parseFloat(item.reducedAmount || 0) / parseFloat(item.totalAmount || 1)) * 100}%`
        })) || [];
        this.setData({ products });
      },
      fail: (err) => {
        console.error('获取首页信息失败:', err);
        wx.showToast({ title: '获取信息失败', icon: 'none' });
      },
      complete: () => {
        this.setData({
          loading: false
        });
        wx.hideLoading();
      }
    });
  },
	// 初始化分享菜单
	initShareMenu() {
		wx.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline'], // 显示分享按钮
		});
	},

	// 点击优惠券
	onClaimCoupon(e) {
		const couponPackageId = this.data.selectedAddress.couponPackageId;

		if (!couponPackageId) return;

		wx.showLoading({ title: '领取中' });

		this.requestClaimCoupon(couponPackageId)
			.then((res) => {
				wx.hideLoading();
				wx.showToast({
					title: res.result?.message || '领取成功',
					icon: 'none',
				});
				this.setData({
					hasClaimed: true
				})
			})
			.catch((err) => {
				wx.hideLoading();
				console.error('领取优惠券失败:', err);
				wx.showToast({ title: '领取失败', icon: 'none' });
			});
	},
	requestClaimCoupon(couponPackageId) {
		return new Promise((resolve, reject) => {
			wx.cloud
				.callFunction({
					name: 'xiaoBangCommonFunction',
					data: {
						claimCouponRequest: {
							openId: this.data.openId,
							couponPackageId: couponPackageId,
						}
					},
				})
				.then((res) => {
					if (res?.result?.code === 200) {
						resolve(res);
					} else {
						reject(res);
					}
				})
				.catch(reject);
		})
	},
	// 更新商品数量
	updateProductQuantity(id, delta) {
		const products = this.data.products.map((product) => {
			if (product.id === id) {
				const newQuantity = product.quantity + delta;
				if (newQuantity >= 1 && newQuantity <= 99) {
					product.quantity = newQuantity;
					product.totalPrice = this.convertJiaoToYuanString(
						this.convertYuanToJiao(product.price) * newQuantity
					);
				}
			}
			return product;
		});

		this.setData({ products });
	},

	// 增加商品数量
	onIncrease(e) {
		const id = e.currentTarget.dataset.index;
		this.updateProductQuantity(id, 1);
	},

	// 减少商品数量
	onDecrease(e) {
		const id = e.currentTarget.dataset.index;
		this.updateProductQuantity(id, -1);
	},

	// 选择地址
	showAddressChooseActionSheet() {
		wx.showActionSheet({
			itemList: this.data.addressList.map((item) => item.addressName),
			success: (res) => {
				const selectedAddressIndex = res.tapIndex;
				const selectedAddress = this.data.addressList[selectedAddressIndex];
				console.log('> showAddressChooseActionSheet', 'selectedAddress', JSON.stringify(selectedAddress));
				// 更新选中的地址
				this.setData({ 
					selectedAddressIndex, 
					selectedAddress,
					// 清空当前数据，避免显示旧数据
					products: [],
					couponItems: [],
					hasClaimed: false,
					loading: true
				});

				// 缓存选中的地址到本地
				wx.setStorageSync('selectedAddress', selectedAddress);

				// 重新获取该学校的信息，传入选中的schoolCode
				this.callGetHomeInfo("0", "0", selectedAddress.addressCode);
			},
			fail: () => {
				wx.showToast({ title: '取消选择', icon: 'none' });
			},
		});
	},

	// 元转角
	convertYuanToJiao(input) {
		const yuan = typeof input === 'string' ? parseFloat(input) : input;
		if (isNaN(yuan)) throw new Error('Invalid input: not a number');
		return Math.round(yuan * 10);
	},

	// 角转元字符串
	convertJiaoToYuanString(jiao) {
		if (typeof jiao !== 'number') throw new Error('Invalid input: not an integer');
		return (jiao / 10).toFixed(1);
	},

	// 砍一刀逻辑
	onBargain(e) {
		// console.log("下单逻辑", e.currentTarget.dataset.index)
		const product = this.data.products.find(product => product.id === e.currentTarget.dataset.index);
		if (product.status !== "onSale") {
			wx.showToast({
				title: '服务暂时未上线',
			})
			return;
		}
		const param = {
			image_url: product.imageUrl,
			productId: product.id,
			count: product.quantity, //购买商品的数量
			fromPage: "order", //order:点击首页的下单进来的；bargin：点击砍价页的下单进来的
			discount_amount: '', //如果是从砍价页进来的，砍价金额传给后端
			participantId: "", //如果是从砍价页进来的，输入生成的砍价id,
			schoolCode: this.data.selectedAddress.addressCode
		}; // 要传递的参数
		// const navigateUrl = '/pages/invite1/index?param=' + encodeURIComponent(JSON.stringify(param));
		// console.log(">>>productList.url",navigateUrl)
		wx.navigateTo({
			url: '/pages/invite1/index?param=' + encodeURIComponent(JSON.stringify(param))
		});
	},

	// 下单逻辑
	onBuy(e) {
		const product = this.data.products.find(product => product.id === e.currentTarget.dataset.index);
		if (product.status !== "onSale") {
			wx.showToast({
				title: '服务暂时未上线',
				icon: 'error'
			})
			return;
		}
		// 零食代买：跳转到楼栋零食铺页
		if (product.id === 'PSnackPickup') {
			wx.navigateTo({
				url: `/pages/buildingSnacksStore/index?schoolCode=${this.data.selectedAddress.addressCode}`
			});
			return;
		}
		console.log("product:", product)
		const param = {
			productId: product.id,
			count: product.quantity, //购买商品的数量
			fromPage: "order", //order:点击首页的下单进来的；bargin：点击砍价页的下单进来的
			discount_amount: '', //如果是从砍价页进来的，砍价金额传给后端
			participantId: product.participantId, //如果是从砍价页进来的，输入生成的砍价id,
			schoolCode: this.data.selectedAddress.addressCode
		}; // 要传递的参数
		wx.navigateTo({
			url: '/pages/placeAnOrder2/placeAnOrder2?param=' + encodeURIComponent(JSON.stringify(param))
		});
	},
	onPopupClose() {
		this.setData({
			showPopup: false
		})
	},
	onPopupBtnTap() {
		// TODO: 此处待完善领取卡包逻辑
		const couponPackageId = this.data.selectedAddress.couponPackageId;
		console.log('> onPopupBtnTap', 'packageId', couponPackageId);
		this.requestClaimCoupon(couponPackageId)
			.then((res) => {
				wx.showModal({
					content: '领券成功!',
					confirmText: '知道了',
					cancelText: '查看卡券',
					complete: (res) => {
						if (res.cancel) {
							wx.navigateTo({
								url: '/pages/coupon/index',
							})
						}
						if (res.confirm) {
						}
					}
				})
			})
			.catch((err) => {
				console.error('领取优惠券失败:', err);
				wx.showToast({ title: '接口异常，领券失败', icon: 'none' });
			}).finally(() => {
				wx.hideLoading();
				this.setData({
					showPopup: false
				})
			});

	},
	onPullDownRefresh() {
    console.log('onPullDownRefresh');
    this.fetchHomeInfo();
	}

});
